package com.itheima.Service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Bean.Dish;
import com.itheima.Bean.DishFlavor;
import com.itheima.Bean.Setmeal;
import com.itheima.Bean.SetmealDish;
import com.itheima.Dao.DishDao;
import com.itheima.Service.DishFlavorService;
import com.itheima.Service.DishService;


import com.itheima.Service.SetmealDishService;
import com.itheima.dto.DishDto;
import com.itheima.exception.CustomException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    @Transactional
    public void remove(List<Long> ids) {
        List<Dish> dishList = this.listByIds(ids);
        for (Dish dish : dishList) {
            if(dish.getStatus()==1){
                throw new CustomException("该菜品未停售，不能删除！！");
            }
        }
        LambdaQueryWrapper<SetmealDish> sdlqw = new LambdaQueryWrapper<>();
        sdlqw.in(SetmealDish::getDishId,ids);
        if(setmealDishService.count(sdlqw) > 0){
            throw new CustomException("当前菜品关联了套餐，不能删除！");
        }
        super.removeByIds(ids);
    }

    @Transactional
    @Override
    public void addDishWithFlavors(DishDto dishDto) {
        this.save(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getDishWithFlavors(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorService.list(lqw);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavors(DishDto dishDto) {
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setId(null);
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }


}
